<?php
/*
*验证码发送
*/
namespace app\home\controller;

use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
header("content-type:application/x-www-form-urlencoded");
class Sms extends Controller
{
    //验证码类
    /*
    *phone         手机号
    *lock          验证锁
    */
    public function phoneCode(){
//        $param=json_decode(file_get_contents('php://input'),true);
        $param  = input('post.');
        if(empty($param['phone'])) return json(array('code'=>300,'msg'=>'手机号不能为空'));
//        if(empty($param['lock'])) return json(array('code'=>300,'msg'=>'lock不能为空'));
        $phone=$param['phone'];
//        $lock=$param['lock'];
        if(!preg_match('/^1[3456789]\d{9}$/',$phone)) return json(array('code'=>300,'msg'=>'手机号码格式错误'));

        $yzm=rand(100000,999999);//验证码
        //验证lock
//        if($lock != self::phone_lock($phone)) return json(['code'=>3009,'msg'=>'系统繁忙，请返回重试']);

        //入库验证码
        self::phone_user($phone,$yzm);


        smsComA('TTEMsgCode',$phone,'金佣先生,'.$yzm);

        return json(array('code'=>200,'msg'=>'成功'));

    }

    //锁机制
    private function phone_lock($m){
        $c=(decoct(substr($m,1,-1)));//取后10为，转为8进制数
        $w=10000+substr($m,7,4);//取后4位+10000
        return substr($c*$w,-5);//取后5位
    }

    //用户验证码
    public function phone_user($phone,$yzm){
        $sphone=num_secret($phone);

        $p=db('phone_yzm')->where("phone='{$sphone}'")->find();
        if($p){
            //更新
            $d['phone_yzm_id']=$p['phone_yzm_id'];
            $d['yzm']=$yzm;
            $d['time']=date('Y-m-d H:i:s',time());
            $d['overtime']=date('Y-m-d H:i:s',time()+60*20);
            $d['date']=date('Y-m-d',time());

            if($d['date']!=$p['date']){
                $d['day_count']=1;
            }else{
                $d['day_count']=$p['day_count']+1;
            }

            db('phone_yzm')->update($d);
        }else{
            //添加
            $d['phone']=$sphone;
            $d['yzm']=$yzm;
            $d['time']=date('Y-m-d H:i:s',time());
            $d['overtime']=date('Y-m-d H:i:s',time()+60*20);
            $d['date']=date('Y-m-d',time());

            db('phone_yzm')->insert($d);
        }
    }


}
